package com.yishusmt.mobsmt.utils;

import com.yishusmt.mobsmt.entity.UrlBodyEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangyi
 * @date 2018/8/11 11:48
 */
@Component
public class HttpClientUtil {
    @Autowired
    private RequestConfig config;

    public UrlBodyEntity connectUrl(String url, Map<String,Object> form) throws IOException {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        //添加基本配置信息
        httpPost.setConfig(config);
        //json数据转换
        String sumbitForm = JacksonUtil.toJSon(form);
        //设置格式
        StringEntity stringEntity = new StringEntity(sumbitForm, "utf-8");
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setEntity(stringEntity);
        String execute = httpClient.execute(httpPost, new BasicResponseHandler());
        UrlBodyEntity urlBodyEntity = JacksonUtil.readValue(execute, UrlBodyEntity.class);
        return urlBodyEntity;
    }
}
